package Client.View;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


import Client.Model.GameModel;

public class GameConfigView extends JPanel implements Observer{

	/**
	 * 
	 */
	private static final long serialVersionUID = 942079744477606334L;

	GameModel model;
	int width;
	int height;
	JPanel configCanvas, top, bottom;
	JButton readyBtn;
	
	JLabel melbl, enemyLbl;
	
	
	public GameConfigView(GameModel model, int width, int height) {
		
		this.model = model;
		this.height = height;
		this.width = width;
		
		model.addObserver(this);
		
		setVisible(true);
		this.setFocusable(true);
		
		setView();
		
		addListeners();
		
	}


	private void addListeners() {
		
		readyBtn.addMouseListener(new MouseAdapter() {
		
			@Override
			public void mousePressed(MouseEvent e) {
				if (GameConfigView.this.model.getBoard().isReadyToStart())
					model.sendConfig();
				else
					JOptionPane.showMessageDialog(GameConfigView.this,"Invalid Configuration!");
			}
		
		});
		
	}

	private void setView() {
		
		setBackground(LoginFrame.DEFAULT_BG_COLOR);
		setMinimumSize(new Dimension(width, height));
		setPreferredSize(new Dimension(width, height));
		
		this.setLayout(null);
		
		readyBtn = new JButton("Ready");
		configCanvas = new ConfigBoardCanvas(model, 600, 400);
		
		top = new JPanel();
		bottom = new JPanel();
			
		top.setBackground(LoginFrame.DEFAULT_BG_COLOR);
		bottom.setBackground(LoginFrame.DEFAULT_BG_COLOR);
		
		top.setBounds(0, 0, width, 80);
		configCanvas.setBounds(0, 80, width, 300);
		bottom.setBounds(0, 380, width, 50);
		
		melbl = new JLabel();
		enemyLbl = new JLabel();
		
		top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS));
		JLabel lbl = new JLabel("Config Board:");
		lbl.setFont(new Font("Arial", Font.BOLD, 22));
		top.add(lbl);
		top.add(melbl);
		top.add(enemyLbl);
		
		bottom.add(readyBtn);
	
		this.add(top);
		this.add(configCanvas);
		this.add(bottom);
		
		
		
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		
		if (model.getGamestate()==GameModel.STATE_SETTING){
			this.setVisible(true);
			
			String str = "Me => " + model.getUsername();
			if (model.isBoardConfigured())
				str += " (ready)";
			
			melbl.setText(str);
			
			
			str = "Enemy => " + model.getEnemy();
			if (model.isEnemyBoardConfigured())
				str += " (ready)";
			
			enemyLbl.setText(str);
			
		}
		else
			this.setVisible(false);

		configCanvas.revalidate();
		configCanvas.repaint();
		
		
		revalidate();
		repaint();
		
	}

}
